package com.ydd.app.action;

import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.whalin.MemCached.MemCachedClient;
import com.ydd.app.bean.common.CommonRequest;
import com.ydd.common.util.CommonInputBean;
import com.ydd.common.util.CommonRetBean;
import com.ydd.common.util.DateJsonValueProcessor;
import com.ydd.common.util.JsonDateValueProcessor;
import com.ydd.common.util.MsgUtils;

/**
 * 共通Action处理
 * @see ActionSupport
 * @version 1.0
 */
@Controller
public class CommonAct {
	
	public static final long serialVersionUID = 9186003359085869491L;
	// 错误日志记录Log
	protected static final Logger  log = Logger.getLogger(CommonAct.class);
	
	public static String RESULTAPP = "app";
	
	public static String CALLBACK = "callback";

	public static String VOICE = "voice";
	public static String PICURL = "picture";
	public static String QUESTIONER = "questioner";
	public static String DOC = "doctor";
	public static String HEAD="head";
	public static String INFO = "info";
	public static String LICE="licence";
	public static String OTHERS="others";
	public static String ZIXUN="zixun";
	public static String TALK="talk";
	public static String INFORMATION="information";
	public static String KNOWLEDGE="knowledge";
	public static String PERSONAL="personal";
	public static String ORDER="order";
	public static String MEDIA="media";
	public static String MESSAGE="message";
	public static String BEGIN_METHOD = "方法执行开始";
	public static String END_METHOD = "方法执行结束";
	public static String PHONE = "400-005-9900";
	//判断用户的咨询者数上限
	public static int QuestionerCount=99999;
	//普通会员  图文资讯医生回答上限
	public static int PaidDocAnswerCount=3;
	//普通会员  图文资讯医生回答上限
	public static double BalanceToScore=100.0;
	/*************************************************
	 * 共通变量定义
	 ************************************************/
	// 消息共通
	@Autowired
	public MsgUtils msgUtils;
	// list用对象
	public List<?> lstBean;
	// bean用对象
	public Object bean;
	// 更新用时间
	public Timestamp timestamp;	
	
	/*************************************************
	 * APP请求参数
	 ************************************************/
	public String m;
	
	/*************************************************
	 * 常量定义
	 ************************************************/
	public static final String TOKENFLG = "tokenFlg";									// 添加了tokencheck的标志
	public static final String STATIC_RET_OK = "0";									// 正常
	public static final String STATIC_RET_ERROR_1000 = "1000";								// 错误
	public static final String STATIC_RET_ERROR_2000 = "2000";								// 错误
	
	public static final String STATIC_RET_ERROR_3000 = "3000";								// password error
	public static final String STATIC_RET_ERROR_3001 = "3001";								// 账号不存在
	public static final String STATIC_RET_ERROR_9999 = "9999";								// token error
	
	public static final int TIMEOUT = 3600000;								// 验证码失效时间
	public static final int FILEWITH=80;									//缩略图大小
	/*************************************************
	 * 系统设置变量及内容
	 ************************************************/
	public static final String PAGE_SIZE = "PAGE_SIZE";								// 分页件数（每页件数）
	
	@Autowired
	public MemCachedClient memcachedClient;
	//  手机效验消息读取 
	public MsgUtils msg =  new MsgUtils();
//  手机效验
	public final Pattern pattern = Pattern.compile(msg.getValue("regexMobile"));
	// 17开头的手机用互易发
	public final Pattern HYpattern = Pattern.compile(msg.getValue("HYregexMobile"));
	
	/**
	 * BEAN转换为JSON数据格式
	 * @param obj
	 * @throws IOException
	 */
	public void CommBeanToJson(Logger log, Object obj, HttpServletResponse response){
		
		// 日期格式转换
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(Date.class,new JsonDateValueProcessor());  
		// 转换为JSON String格式
		String ret = JSONObject.fromObject(obj, jsonConfig).toString();

	    // JSON数据格式返回
	 	try {
	 		response.setContentType("text/html;charset=UTF-8"); 
			response.getWriter().write(ret);
		} catch (IOException e) {
			CommSysErrorLog(log, e);
		}
	}
	
	/**
	 * 参数bean获取
	 * @param request
	 * @throws IOException
	 */
	public void getParameterBean(HttpServletRequest request, CommonRequest bean){
		try {
				BeanUtils.populate(bean,request.getParameterMap());
				String ab=msgUtils.getValue("pageCountElse");
				int i=Integer.parseInt(ab);
				bean.setPageCount(i);
		} catch (IllegalAccessException e) {
			//  Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			//  Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**  
	 *   
	 * @方法名：valueIsNotNull  
	 * @方法描述：   判断String参数不为空
	 * @参数：  str
	 * @参数描述：  参数
	 *   
	 */
	public boolean valueIsNotNull(final String str){
		if(!"".equals(str) && str!=null){
			return true;
		}
		return false;
	}
	/**
	 * BEAN转换为JSON数据格式
	 * @param obj
	 * @throws IOException
	 */
	public void CommBeanToJson(Object obj, HttpServletResponse response,String callback){
		JsonConfig config=new JsonConfig();  
	    config.registerJsonValueProcessor(Timestamp.class, new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));  
		// 转换为JSON String格式
		String ret = JSONObject.fromObject(obj,config).toString();
        
	    // JSON数据格式返回
	 	try {
	 		if(valueIsNotNull(callback)){
	 			response.setContentType("text/html;charset=UTF-8"); 
				response.getWriter().write(callback+"("+ret+")");
	 		}else {
	 			response.setContentType("text/html;charset=UTF-8"); 
				response.getWriter().write(ret);
			}
		} catch (IOException e) {
			
		}
	}
	
	public void CommBeanToJson1(Object obj, HttpServletResponse response,String callback){
		JsonConfig config=new JsonConfig();  
	    config.registerJsonValueProcessor(Timestamp.class, new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));  
		// 转换为JSON String格式
		String ret = JSONObject.fromObject(obj,config).toString();
        
	    // JSON数据格式返回
	 	try {
	 		response.setContentType("text/html;charset=UTF-8"); 
			response.getWriter().write(ret);
			
		} catch (IOException e) {
			
		}
	}
	
	/**
	 * 初始化处理
	 */
	public void init(){
	
		// 更新时间
//		timestamp = commService.getDateDow();
		
		// 防止NULL错误
		if(m == null) m = "";
	}
	
	/**
	 * 共通ERROR处理
	 * @param msgId
	 * @return
	 */
	public Object CommRetError(String msgId){
		// 共通返回接口
		CommonRetBean ret = new CommonRetBean();
		// 执行结果返回
		ret.setCode(STATIC_RET_ERROR_1000);
		// 设定错误信息
		ret.setMessage(this.msgUtils.getValue(msgId));
		
		// 返回共通BEAN
		return ret;
	}
	
	/**
	 * 前台参数请求 共通ERROR处理
	 * @param msgId
	 * @return
	 */
	public Object CommRetErrorUI(String msgId){
		// 共通返回接口
		CommonRetBean ret = new CommonRetBean();
		// 执行结果返回
		ret.setCode(STATIC_RET_ERROR_1000);
		MsgUtils  msgUtils = new MsgUtils();
		// 设定错误信息
		ret.setMessage(msgUtils.getValue(msgId));
		// 返回共通BEAN
		return ret;
	}
	
	public Object CommRetError(String msgId,Object[] obj){
		// 共通返回接口
		CommonRetBean ret = new CommonRetBean();
		// 执行结果返回
		ret.setCode(STATIC_RET_ERROR_1000);
		// 设定错误信息
		ret.setMessage(this.msgUtils.getValue(msgId, obj));
		// 返回共通BEAN
		return ret;
	}
	
	/**
	 * 系统错误日志出力(文件)
	 * @param log
	 * @param msgId
	 * @param e
	 */
	public void CommSysErrorLog(Logger log, Exception e){
		
		String out = "[" + this.getClass().getName() + "] ";
		for(int i = e.getStackTrace().length - 1; i > -1; i--){
			if((e.getStackTrace()[i]).getClassName().indexOf("movingmedia") > 0){
				out = out + e.getStackTrace()[i].getMethodName() + "->";
			}
		}
		// 文件出力
		log.error(out + e.getMessage());
		// 平台打印
		e.printStackTrace();
	}
	
	
	/**
	 * bean转字符串
	 * @param bean
	 * @return String
	 */
	public static String beanToString(Object b) {
        StringBuilder json = new StringBuilder();
        PropertyDescriptor[] props = null;
        try {
            props = Introspector.getBeanInfo(b.getClass(), Object.class).getPropertyDescriptors();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (props != null) {
            for (int i = 0; i < props.length; i++) {
                try {
                    json.append((String)props[i].getReadMethod().invoke(b));
                    json.append(",");
                } catch (Exception e) {
                }
            }
            
        } 
        
        return json.toString();
    }

    //*********************************************
    // 以下为代码自动生成
    //*********************************************
	public List<?> getLstBean() {
		return lstBean;
	}

	public void setLstBean(List<?> lstBean) {
		this.lstBean = lstBean;
	}

	public Timestamp getTimestamp() {
		return timestamp;
	}

	public void setTimestamp(Timestamp timestamp) {
		this.timestamp = timestamp;
	}

	public Object getBean() {
		return bean;
	}

	public void setBean(Object bean) {
		this.bean = bean;
	}
	
}
